package com.yzw.reconnheart;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 客户端监听类，通过 实现ChannelFutureListener来实现客户端自动重新链接
 * @USER: root
 * @DATE: 2023/2/9 22:27
 **/
public class ListenerClientReconnHeart implements ChannelFutureListener {
    /**
     * 定义重连的客户端
     */
    private AppClientReconnHeart appClientReconnHeart=new AppClientReconnHeart("127.0.0.1",18080);
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        // 监听与服务端链接不正常时，进行重新链接当链接不正常时
        if (!channelFuture.isSuccess()){
            EventLoop loop=channelFuture.channel().eventLoop();
            ScheduledFuture<?> scheduledFuture=loop.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(">>>自动启动客户端，开始链接服务器.....");
                        appClientReconnHeart.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            },5, TimeUnit.SECONDS);
        }else {
            System.out.println(">>>链接服务器成功.....");
        }

    }
}
